<template>
  <div class="tab_home">
    <order-broadcast/>
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <div class="logo">
        <img src="@/assets/images/logo.png" width="50px" height="14px">
      </div>
      <div class="tal_class_searchBox">
        <van-search
          placeholder="点击进行商品搜索"
          background="#00CC66"
          @click="$router.push({ name: 'search' })"
        />
      </div>

      <sign-board v-once v-if="user"/>
      <shop-subject/>
      <shop-info-group v-once v-if="shopValid" class="interval_bot" @click="onSelShop"/>
      <div class="shop_btn" v-else-if="!user.upshopTid">
        <van-button round size="large" type="danger" @click="onSelShop">选择团长</van-button>
      </div>
    </van-pull-refresh>
      <!-- <van-tabs sticky v-if="shopValid && !shopSleep" @click="xiaolu"> -->
        <van-tabs sticky v-if="shopValid && !shopSleep" @disabled="forbidden">
        <van-tab title="今日上新">
          <goods-list :shopId="user.upshopTid" :type="0" @addCart="addCart"/>
        </van-tab>

        <van-tab title="热销爆款">
          <goods-list :shopId="user.upshopTid" :type="1" @addCart="addCart"/>
        </van-tab>
        <van-tab title="小鹿集市" disabled></van-tab>
        <!-- <van-tab title="会员专区">
          <goods-list :shopId="user.upshopTid" :type="2" @addCart="addCart" />
        </van-tab>-->
      </van-tabs>
    
    <home-footer v-once v-if="footer" :qrcode="footer.qrcode" :phones="footer.phones"/>
    <pop-shop-sel
      :show="showSelShop"
      @onShow="onShowSelShop($event)"
      @changeShop="onChangeShop($event)"
    />
    <!-- 多规格选择 -->
    <van-sku
      v-if="skuData"
      v-model="showSku"
      :sku="skuData.sku"
      :goods="skuData.goods"
      :hide-stock="skuData.sku.hide_stock"
      :quota="0"
      :quota-used="0"
      @add-cart="addSkuCart"
      @buy-clicked="doBuyNow"
      class="sku_panel"
      ref="skuDom"
      @sku-selected="skuChange"
    >
      <template slot="sku-header-price" slot-scope="props">
        <div v-if="!props.selectedSkuComb" class="van-sku__goods-price">
          <span class="van-sku__price-symbol">￥</span>
          <span class="van-sku__price-num">{{ props.price }}</span>
          <template v-if="skuData.sku.vipprice && skuData.goods.isvip">
            <span class="van-sku__price-symbol" style="margin-left: 10px;">会员￥</span>
            <span class="van-sku__price-num">{{skuData.sku.vipprice.toFixed(2)}}</span>
          </template>
        </div>
        <div v-else class="van-sku__goods-price">
          <span class="van-sku__price-symbol">￥</span>
          <span class="van-sku__price-num">{{ props.price }}</span>
          <template v-if="props.selectedSkuComb.vipprice && skuData.goods.isvip">
            <span class="van-sku__price-symbol" style="margin-left: 10px;">会员￥</span>
            <span class="van-sku__price-num">{{props.selectedSkuComb.vipprice.toFixed(2)}}</span>
          </template>
        </div>
      </template>
      <template slot="sku-actions" slot-scope="props" style="z-index: 2000;">
        <div class="van-sku-actions">
          <van-button bottom-action @click="addSkuCart">加入购物车</van-button>
        </div>
      </template>
    </van-sku>
    <transition name="fade">
      <van-icon name="arrowupcircle" class="backTop red" @click.native="backTop" v-show="showArrow"></van-icon>
    </transition>
    <!-- <audio v-if="isPlayTime" autoplay ref="audioPlayer"><source src="@/assets/audio/bg.mp3"></audio> -->
    <!-- 引导添加小程序 -->
    <van-popup v-model="showLead" class="miniAdd">
      <img src="@/assets/images/addmini.png" alt class="addMini">
      <van-icon name="close" class="addclose" size="25px" color="#fff" @click="addClose"/>
    </van-popup>
    <!-- 弹券 -->
    <van-popup v-model="showQuan" class="quan" v-if="quanData">
      <div>
        <img src="@/assets/images/quan.png" alt class="quanBg">
        <van-icon name="close" class="close" size="22px" color="#fff" @click="quanClose"/>
        <img src="@/assets/images/quanLog.png" alt class="quanLog">
        <img src="@/assets/images/get.png" alt class="linqu" @click="receive">
        <div class="explain">领取后可在会员中心“我的优惠券”中查看明细</div>
        <div class="quanCon">
          <div style="font-size: 10px;" class="danQuan" v-if="quanData.length == 1">
            <div class="quanLeft">
              <span class="danQuanMon" v-if="quanData[0].type === 1">
                ￥
                <span class="quanMon">{{quanData[0].amount}}</span>
              </span>
              <span class="danQuanMon" v-else>
                <span class="quanMon">{{(10 - quanData[0].amount / 10).toFixed(1)}}</span>折
              </span>
            </div>
            <div class="quanRight">
              <div class="danName">{{quanData[0].ticketName}}</div>
              <div
                class="condition_value"
              >{{quanData[0].condition ? "满" + quanData[0].condition + "元可用" : "无使用门槛"}}</div>有效期:
              <span>{{quanData[0].startTime | dateFormat('YYYY.MM.DD')}} - {{quanData[0].endTime | dateFormat('YYYY.MM.DD')}}</span>
            </div>
          </div>
          <span v-if="quanData.length > 1" class="giftBag">优惠券包</span>
        </div>
      </div>
    </van-popup>
    <!-- 券包弹框详情 -->
    <van-popup v-model="showBag" class="quanBag">
      <van-icon name="close" class="bagclose" size="22px" color="#fff" @click="bagClose"/>
      <!-- 优惠券包 -->
      <div class="bagDiv">
        <ul class="bagUl">
          <li v-for="(item,index) in quanData" :key="index">
            <div class="quanBagLeft">
              <div class="bagMonPar">
                <span class="bagMon" v-if="item.type === 1">
                  ￥
                  <span class="bagMoney">{{item.amount}}</span>
                </span>
                <span class="bagMon" v-else>
                  <span class="bagMoney">{{(10 - item.amount / 10).toFixed(1)}}</span>折
                </span>
              </div>
              <div>{{item.condition ? "满" + item.condition + "元可用" : "无使用门槛"}}</div>
            </div>
            <div class="quanBagRight">
              <div class="bagName">{{item.ticketName}}</div>
              <div>有效期：{{item.startTime | dateFormat('YYYY.MM.DD')}}-{{item.endTime | dateFormat('YYYY.MM.DD')}}</div>
            </div>
          </li>
        </ul>
        <img src="@/assets/images/bagSure.png" alt @click="bagSure" class="bagSure">
      </div>
    </van-popup>
  </div>
</template>

<script>
import { HOME_FOOTER, BIND_SHOP, CART_ADD, ACCESS_LOG } from "@/api/shop";

import { USER_PROFILE } from "@/api/user";
import { USER_TICKETPOP, TICKETPOP_CONVERSION } from "@/api/order";

import { WXJS_CONFIG } from "@/api/global";
import { GOODS_DETAIL } from "@/api/goods";
import SignBoard from "./tabbar-home-sign-board";
import ShopInfoGroup from "./tabbar-home-shop-info";
import ShopSubject from "./tabbar-home-subject";
import HomeFooter from "./tabbar-home-footer";
import OrderBroadcast from "./tabbar-home-broadcast";
import GoodsList from "@/vue/components/goods-list/";
import loadMore from "@/vue/mixin/list-load-more";
import {
  Search,
  Toast,
  Tabs,
  Tab,
  Sku,
  PullRefresh,
  Popup,
  Button
} from "vant";
import wxConfig from "@/vue/mixin/wx-config";
import PopShopSel from "@/vue/components/pop-shop-sel/";
import skuData from "@/vue/mixin/sku-data";
import scrollFixed from "@/vue/mixin/scroll-fixed";
import buyAction from "@/vue/mixin/buy-action";
import moment from "moment";
import getConfig from "@/vue/mixin/get-config";

export default {
  mixins: [loadMore, skuData, scrollFixed, wxConfig, buyAction, getConfig],
  data() {
    return {
      footer: null,
      searchKey: null,
      subject: null,
      showSelShop: false,
      shopValid: false,
      shopSleep: false,
      isLoading: false,
      isNianHuo: false,
      showQuan: true,
      showLead: false, //引导添加小程序的提示
      showBag: false, //券包的展示
      quanData: "", //券的数据
      quanId: [], //券的id
      bannerWidth: "",
      isxiaolu: false
    };
  },
  watch: {
    showSku(e) {
      //5.14 修该单位
      if (e) {
        this.$nextTick(() => {
          let el = this.$refs.skuDom.$el.getElementsByClassName(
            "van-sku__stock"
          )[0];
          let str = "剩余" + this.skuData.sku.stock_num + this.skuData.sku.unit;
          el.innerText = str;
        });
      }
    }
  },
  computed: {
    isPlayTime() {
      const played = this.$util.getLocalStorage("playback");

      if (played) {
        return false;
      }

      this.$util.setLocalStorage("playback", true);
      const now = Date.now();
      const start = 1544961600000; //2018-12-16 20:00
      const end = 1545048000000; //2018-12-17 20:00
      return now >= start && now < end;
    }
  },
  created() {
    //商品和店铺码切换(根据路径参数)
    if (this.$route.query.tid) {
      this.onChangeShop(this.$route.query.tid);
    }

    //引导出现次数(一周出现一次)
    //小程序的环境中出现引导
    this.isWxApp().then(result => {
      if (result) {
        if (this.$util.getLocalStorage("timeDif")) {
          let time = new Date().getTime();
          let disTime = this.$util.getLocalStorage("timeDif") - time;
          //计算相差的天数
          let day = Math.ceil(disTime / 1000 / 60 / 60 / 24);
          if (day >= 8) {
            this.showLead = true;
          }
        } else {
          this.$util.setLocalStorage("timeDif", new Date().getTime());
          this.showLead = true;
        }
      }
    });
    //进行微信签名
    this.wxconfig();

    //TODO 要等切完店执行
    const shopId = this.user.upshopTid;
    if (!shopId) {
      this.showSelShop = true;
    } else if (this.getShop()) {
      this.validateShop();
    } else {
      this.$reqGet(USER_PROFILE, { id: this.user.id, getShop: true }).then(
        res => {
          this.saveShop(res.data.shop);
          this.validateShop();
        }
      );
    }
    //底部广告注释
    this.initViews();
    this.addAccessLog();
    // 弹券
    this.showFrame();
  },
  activated() {
    window.tabbar && (window.tabbar.show = true);
    this.getGlobalShare().then(share => {
      const url =
        this.getUri() +
        "register/invite?teamId=" +
        this.user.upshopTid +
        "&cid=" +
        this.user.centreId +
        "&redirect=" +
        encodeURIComponent(share.shareUrl ? share.shareUrl : "/home") +
        "&code=" +
        this.user.myCode;
      this.wxShare(
        this.replaceShare(share.shareTitle),
        share.shareDesc,
        url,
        share.shareIcon
      );
    });
  },
  methods: {
    //关闭添加小程序
    addClose() {
      if (this.quanData && (this.showQuan || this.showBag)) {
        this.showLead = true;
      } else {
        this.showLead = false;
      }
    },
    //选择规格变化
    skuChange(e) {
      //5.14 修该单位
      this.$nextTick(() => {
        let el = this.$refs.skuDom.$el.getElementsByClassName(
          "van-sku__stock"
        )[0];
        let str = "剩余" + e.selectedSkuComb.stock_num + this.skuData.sku.unit;
        el.innerText = str;
      });
    },
    // 券包确定
    bagSure() {
      this.showBag = false;
      this.$router.push({ path: "/user/orderEle/list/1" });
    },
    //点击立即领券，关闭弹框并且跳转到 我的优惠券进行查看
    receive() {
      this.$reqGet(TICKETPOP_CONVERSION, {
        mId: this.user.id,
        tickets: this.quanId
      }).then(res => {
        this.showQuan = false;
        if (this.quanData.length > 1) {
          this.showBag = true;
          return;
        }
        this.$router.push({ path: "/user/orderEle/list/1" });
      });
    },
    //点击关闭按钮将弹出的优惠券关闭
    quanClose() {
      this.showQuan = false;
    },
    bagClose() {
      this.showBag = false;
    },
    // 判断是否含有弹框
    showFrame() {
      if (new Date() > Date.parse("2019-06-16 19:00:00".replace(/-/g, "/"))) {
        this.isxiaolu = true;
      }
      this.$reqGet(USER_TICKETPOP, {
        centerId: this.user.centreId,
        memberId: this.user.id
      }).then(res => {
        this.quanData = res.data.data;
        this.quanId = [];
        if (this.quanData) {
          this.quanData.forEach(item => {
            this.quanId.push(item.id);
          });
        }
      });
    },
    nianhuo() {
      console.log(this.isNianHuo);
    },

    initViews() {
      this.$reqGet(
        HOME_FOOTER,
        { centerId: this.user.centreId },
        { hideLoading: true }
      ).then(res => {
        this.footer = res.data.data;
      });
    },

    onSubject(id) {
      this.$router.push({
        path: `/items/subject/${id}`
      });
    },

    onSelShop() {
      this.showSelShop = true;
    },

    onShowSelShop(show) {
      this.showSelShop = show;
    },
    //切换商店
    onChangeShop(shopId) {
      if (this.user.upshopTid == shopId || this.user.isteam == 3) {
        return;
      }
      this.$reqPost(BIND_SHOP, {
        memberId: this.user.id,
        teamId: shopId,
        time: new Date().getTime()
      }).then(res => {
        this.user.upshopTid = shopId;
        const centerId = res.data.data;
        this.user.centreId = centerId;
        this.saveUser(this.user);
        window.location.href =
          "https://m.jinzhishenghuo.com/wemall/?id=" + 10000 * Math.random();
        // window.location.href = 'https://t.liyboo.com/wemall/?id='+ 10000*Math.random();
        //window.location.href = window.location.href + "?id="+ 10000*Math.random();
      });
    },

    async addAccessLog() {
      let first = this.$util.getSessionStorage("firstAccess") || true;

      if (first) {
        this.$reqPost(ACCESS_LOG, {
          mid: this.user.id,
          accessContent: "访问微商城主页"
        }).then(res => {
          if (res.data.data > 0) {
            this.$util.setSessionStorage("firstAccess", false);
          }
        });
      }
    },

    validateShop() {
      const check = this.checkShop();
      //不是团长或者禁用
      if (check === -1) {
        const shop = this.getShop();
        this.$dialog
          .alert({ message: shop.tXiaoqu + " 已经关闭，请重新选择团长" })
          .then(() => {
            delete this.user.upshopTid;
            this.showSelShop = true;
          });
      } else {
        this.shopValid = true;
      }
    },

    replaceShare(value) {
      if (!value) {
        return value;
      }

      return value.replace(/{tXiaoqu}/, this.getShop().tXiaoqu);
    },

    onRefresh() {
      window.location.href =
        window.location.href + "?id=" + 10000 * Math.random();
    },
    // 跳转小鹿集市页面
    // xiaolu(type) {
    //   if (type == 2) {
    //     this.$router.push({
    //       path: "/xiaolu"
    //     });
    //   }
    // },
    forbidden(){
      // console.log("我是禁用标签")
      this.$router.push({
          path: "/xiaolu"
        });
    }
  },

  components: {
    [SignBoard.name]: SignBoard,
    [ShopInfoGroup.name]: ShopInfoGroup,
    [ShopSubject.name]: ShopSubject,
    [HomeFooter.name]: HomeFooter,
    [OrderBroadcast.name]: OrderBroadcast,
    [GoodsList.name]: GoodsList,
    [Search.name]: Search,
    [Tabs.name]: Tabs,
    [Tab.name]: Tab,
    [PopShopSel.name]: PopShopSel,
    [Sku.name]: Sku,
    [PullRefresh.name]: PullRefresh
  }
};
</script>


<style lang="scss" scoped>
.tab_home {
  // .xiaolu {
  //   .van-tab--disabled {
  //       color:#7d7e80;
  //   }
  // }
  
  .miniAdd {
    background-color: transparent;
    width: 270px;
    transform: translate3d(-50%, -53%, 0);
    -webkit-transform: translate3d(-50%, -53%, 0);
    .addMini {
      width: 100%;
      height: 100%;
    }
    .addclose {
      left: 50%;
      transform: translateX(-50%);
      margin-top: 20px;
    }
  }
}
.quanLeft {
  float: left;
  width: 60px;
  padding-right: 5px;
  text-align: right;
  font-size: 14px;
  padding-top: 5px;
  box-sizing: border-box;
  .quanMon {
    font-size: 23px;
    font-weight: 900;
  }
}
.quanRight {
  float: right;
  color: #76797a;
  font-size: 9px;
  text-align: left;
  line-height: 14px;
  padding-top: 5px;
  box-sizing: border-box;
  .danName {
    color: #000;
    font-size: 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.quanBag {
  width: 280px;
  height: 450px;
  font-size: 12px;
  color: gray;
  background-color: transparent;
  overflow-y: visible;
  background-image: url("../../assets/images/bagBg.png");
  background-repeat: no-repeat;
  background-position: 0 0;
  background-size: 280px 450px;
  padding: 0 10px;
  .bagSure {
    transform: translateX(9%);
  }
  .bagclose {
    position: absolute;
    right: 139px;
    top: -35px;
  }
  .bagDiv {
    position: absolute;
    top: 140px;
    left: 30px;
  }
  .bagUl {
    padding-bottom: 10px;
    li {
      padding: 10px;
      margin-top: 4px;
      overflow: hidden;
      background-color: #fff;
      border-radius: 6px;
    }
  }
  .quanBagLeft {
    float: left;
    width: 80px;
    .bagMonPar {
      margin-bottom: 5px;
      .bagMon {
        color: #f00;
        font-size: 15px;
        .bagMoney {
          font-size: 21px;
          font-weight: 900;
        }
      }
    }
  }
  .quanBagRight {
    float: right;
    width: 120px;
    .bagName {
      color: #000;
      margin-bottom: 5px;
      font-size: 15px;
    }
  }
}
.coupon_panel {
  display: flex;
  font-size: 12px;
}

.amount_text {
  flex: 1;
  padding: 10px 0;

  .amount_value,
  .discount_value {
    color: $red;
    font-size: 10px;
  }

  .amount_value ::before {
    content: "¥";
    font-size: 8px;
    margin-right: 3px;
  }

  .condition_value {
    color: gray;
    font-size: 10px;
    margin-top: 5px;
  }
}

.title_text {
  flex: 2;
  padding: 10px 0;

  .title_value {
    font-size: 10px;
  }
  .expire_value {
    color: gray;
    font-size: 10px;
    margin-top: 5px;
  }
  .status_value {
    text-align: right;
    font-size: 10px;
    color: brown;
    margin-left: 20px;
  }
}
.quan {
  width: 322px;
  height: 300px;
  background-color: rgba(0, 0, 0, 0);
  overflow: visible;
  > div {
    position: relative;
    width: 100%;
    height: 100%;
    .quanBg {
      width: 100%;
    }
    .close {
      position: absolute;
      right: 133px;
      top: -35px;
      background-color: rgba(0, 0, 0, 0);
    }
    .quanLog {
      position: absolute;
      width: 86px;
      top: 61px;
      left: 50%;
      transform: translateX(-35%);
    }
    .linqu {
      position: absolute;
      width: 100px;
      bottom: 50px;
      left: 50%;
      transform: translateX(-35%);
    }
    .explain {
      position: absolute;
      width: 212px;
      bottom: 3px;
      text-align: center;
      left: 50%;
      transform: translateX(-45%);
      font-family: "思源黑体 CN";
      color: #7f1e21;
      font-size: 10px;
    }
    .quanCon {
      position: absolute;
      width: 197px;
      top: 85px;
      left: 50%;
      height: 58px;
      text-align: center;
      transform: translateX(-43%);
      .danQuan {
        position: absolute;
        width: 100%;
        top: 50%;
        height: 87%;
        transform: translateY(-37%);
        text-align: center;
        .danQuanMon {
          color: #f00;
          font-size: 12px;
        }
      }
      .giftBag {
        display: inline-block;
        color: #f00;
        font-size: 28px;
        font-weight: 900;
        margin-top: 20px;
      }
    }
  }
}
.new {
  color: red;
}

.interval_bot {
  margin-bottom: 10px;
}

.logo {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: $green;
  height: 44px;
  float: left;
  padding-left: 5px;
}
.tal_class_searchBox {
  width: 100%;
  position: relative;
}

.shop_btn {
  text-align: center;
  padding: 10px;
}
</style>
<style lang="scss">
    .van-tab--disabled {
        color:#7d7e80;
    }
</style>